const imagemin = require('imagemin').default;
const imageminMozjpeg = require('imagemin-mozjpeg').default;
const imageminPngquant = require('imagemin-pngquant').default;
const fs = require('fs');
const path = require('path');

const sourceDir = path.join(__dirname, '../static');
const targetDir = path.join(__dirname, '../static/optimized');

// 确保目标目录存在
if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true });
}

// 优化图片
(async () => {
    try {
        const files = await imagemin([`${sourceDir}/**/*.{jpg,jpeg,png}`], {
            destination: targetDir,
            plugins: [
                imageminMozjpeg({
                    quality: 75,
                    progressive: true
                }),
                imageminPngquant({
                    quality: [0.6, 0.8]
                })
            ]
        });

        console.log('图片优化完成！');
        console.log('优化后的文件：');
        files.forEach(file => {
            const originalSize = fs.statSync(file.sourcePath).size;
            const optimizedSize = fs.statSync(file.destinationPath).size;
            const saved = ((originalSize - optimizedSize) / originalSize * 100).toFixed(2);
            console.log(`${path.basename(file.sourcePath)}: ${(originalSize/1024).toFixed(2)}KB -> ${(optimizedSize/1024).toFixed(2)}KB (节省 ${saved}%)`);
        });
    } catch (error) {
        console.error('优化过程中出错：', error);
    }
})(); 